var pageSize = 20;
var startIndex = 0;

var searchDs;
var searchKeyWordField;
var nationCombobox;
var searchModCombobox;
var main_Panel;

function getSearchForm() {
	var nationStore = new Ext.data.SimpleStore({
		fields : [ 'value', 'description' ],
		data : [ [ '全部', '全部' ], [ '大陆', '大陆' ], [ '香港', '香港' ],
				[ '美国', '美国' ], [ '韩国', '韩国' ], [ '台湾', '台湾' ], [ '英国', '英国' ],
				[ '法国', '法国' ], [ '加拿大', '加拿大' ] ]
	});

	nationCombobox = new Ext.form.MultiComboBox({
		id : 'vTypeCombo',
		editable : false,
		name : 'vTypeCombo',
		displayField : "description",
		labelSeparator : '',
		labelWidth : 40,
		labelAlign : 'left',
		valueField : 'value',
		displaySeparator : ' ',
		valueSeparator : ' ',
		hiddenName : 'hiddenNameId',
		fieldLabel : '国籍:',
		mode : 'local',
		store : nationStore,
		triggerAction : 'all',
		width : 130,
		emptyText : TXT_vod_category_empty_msg,
		listeners : {
			'change' : loadData
		}
	});

	// sets default value
	var firstValue = nationStore.getRange()[0].data.value;
	nationCombobox.setValue(firstValue);

	var searchModStore = new Ext.data.SimpleStore({
		fields : [ 'value', 'description' ],
		data : [ [ 'database', '数据库' ], [ 'index', '索引库' ] ]
	});

	searchModCombobox = new Ext.form.ComboBox({
		id : 'searchModCombobox',
		editable : false,
		name : 'searchModCombobox',
		displayField : "description",
		labelSeparator : '',
		labelWidth : 40,
		labelAlign : 'left',
		valueField : 'value',
		fieldLabel : '搜索源:',
		mode : 'local',
		store : searchModStore,
		triggerAction : 'all',
		triggerClass : 'x-form-trigger2',
		width : 130,
		emptyText : '',
		listeners : {
			'change' : loadData
		}
	});

	// sets default value
	firstValue = searchModStore.getRange()[0].data.value;
	searchModCombobox.setValue(firstValue);

	searchKeyWordField = new Ext.form.TextField(
			{
				fieldLabel : '<b style="color:red;">* </b> '
						+ TXT_search_keyword_label,
				id : 'keyword',
				name : 'keyword',
				allowBlank : false,
				afterRender : function() {
					searchKeyWordField.getEl().on('keyup', function(e) {
						e.stopEvent();
						if ((e.getKey() == Ext.EventObject.ENTER)) {
							searchButtonClick();
						}
					})
				}
			});

	var searchButton = new Ext.Button({
		id : "searchButton",
		text : TXT_search_button_text,
		type : "button",
		cls : 'x-toolbar',
		handler : searchButtonClick
	});

	var searchForm = new Ext.FormPanel({
		frame : true,
		layout : 'column',
		labelAlign : 'right',
		buttonAlign : 'left',
		labelWidth : 60,
		border : false,
		region : 'north',
		height : 60,
		tbar : [
				"-",
				"<span style='font-weight:bold;font-size:11px'>"
						+ TXT_person_manager + "</span>", '->' ],
		style : 'text-align:right;',
		items : [ {
			columnWidth : .99,
			html : "&nbsp;"
		}, {
			layout : 'form',
			width : 195,
			style : 'margin:4px 0 0 0;',
			labelAlign : 'left',
			items : [ searchModCombobox ]
		}, {
			layout : 'form',
			width : 195,
			style : 'margin:4px 0 0 0;',
			labelAlign : 'left',
			items : [ nationCombobox ]
		}, {
			layout : 'form',
			width : 200,
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ searchKeyWordField ]
		}, {
			layout : 'form',
			width : 50,
			style : 'margin:4px 0 0 0;',
			buttonAlign : 'left',
			items : [ searchButton ]
		} ]
	});

	return searchForm;
}

function getSearchGrid() {
	var searchSm = new Ext.grid.RowSelectionModel({
		singleSelect : true
	});
	var searchCm = new Ext.grid.ColumnModel(
			[
					{
						header : TXT_person_name,
						dataIndex : 'name',
						width : 80,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : '海报',
						dataIndex : 'avatar',
						width : 80,
						renderer : function(v) {
							return "<div><img src='" + v
									+ "' width=60 height=60></img></div>";
						}
					},
					{
						header : '<div style="text-align:center" height="20">'
								+ TXT_Common_Operation + '</div>',
						dataIndex : 'code',
						width : 80,
						renderer : function(v) {
							return "<div width='100%' style='text-align:center'><a style='color:blue;text-decoration:underline;cursor:pointer' onClick=getPersonDetail('"
									+ v
									+ "')>"
									+ TXT_common_detail
									+ "</a></div>";
						}
					},
					{
						header : '<div style="text-align:center" height="20"></div>',
						dataIndex : 'code',
						width : 160,
						renderer : function(v) {
							var mod = searchModCombobox.getValue();
							if (mod == 'index') {
								v = v.split('_')[1];
							}
							return "<div width='100%' style='text-align:center' id='"
									+ v
									+ "'><a style='color:blue;text-decoration:underline;cursor:pointer' onClick=openUploadAvataForm('"
									+ v
									+ "')>"
									+ TXT_person_avatar_upload
									+ "</a></div>";
						}
					} ]);

	searchDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.ExJsonReader({
			root : 'results',
			totalProperty : 'totalCount',
			id : 'id',
			fields : [ {
				name : 'name'
			}, {
				name : 'avatar'
			}, {
				name : 'code'
			} ]
		})
	});

	searchDs.baseParams = {
		'cmd' : 'info',
		'action' : 'findInfoFromEngine'
	};

	var searchGrid = new Ext.grid.GridPanel(
			{
				border : false,
				region : 'center',
				ds : searchDs,
				cm : searchCm,
				sm : searchSm,
				stripeRows : true,
				loadMask : {
					msg : 'searching...'
				},
				viewConfig : {
					forceFit : true
				},
				listeners : {
					'keydown' : function(e) {
						e.stopEvent();
						PagingToolbar_KeyEvent(Ext
								.getCmp('searchGridPagingToolbar'), e);
					}
				},
				bbar : new Ext.PagingToolbar(
						{
							id : 'searchGridPagingToolbar',
							pageSize : pageSize,
							height : 18,
							store : searchDs,
							displayInfo : true,
							displayMsg : TXT_common_paging,
							emptyMsg : TXT_common_no,
							onPagingKeydown : function(e) {
								PagingToolbar_KeyEvent(this, e);
							},
							onClick : function(which) {
								switch (which) {
								case 'prev':
									startIndex = startIndex - pageSize;
									break;
								case 'first':
									startIndex = 0;
									break;
								case 'next':
									startIndex = startIndex + pageSize;
									break;
								case 'last':
									startIndex = ((this.store.getTotalCount() / pageSize) | 0)
											* pageSize;
									break;
								default:
								}

								// Gets data
								loadData();
							}
						})
			});

	return searchGrid;
}

function PagingToolbar_KeyEvent(thisPagingToolbar, e) {
	if ((e.getKey() == Ext.EventObject.ENTER)) {
		var currPage = thisPagingToolbar.readPage();
		var totalPage = thisPagingToolbar.getPageData().pages;

		if (currPage > totalPage) {
			Ext.Msg.alert(TXT_common_hint, TXT_Common_Correct_PageNum);
			return;
		} else {
			if (currPage <= 0) {
				startIndex = 0;
			} else {
				startIndex = (currPage - 1) * pageSize;
			}

			// Gets data
			loadData();
		}
	}
	return;
}

function displaySearchPanel() {

	var searchForm = getSearchForm();
	var searchGrid = getSearchGrid();
	main_Panel = new Ext.Panel({
		border : false,
		region : 'center',
		layout : 'border',
		margins : '5 5 5 5',
		cmargins : '5 5 5 5',
		items : [ searchForm, searchGrid ]
	});

	BestvSearch.glb_mainPanel.add(main_Panel);
	BestvSearch.drawMainFrame(TXT_app_name + ' - ' + TXT_search_title, null);
}

Ext.onReady(displaySearchPanel);

function searchButtonClick() {
	startIndex = 0;

	// Gets data
	loadData();
}

function loadData() {
	var mod = searchModCombobox.getValue();
	if (mod == 'index') {
		loadDataFromIndex();
	} else {
		loadDataFromDB();
	}
}

function loadDataFromIndex() {
	var keyWord = searchKeyWordField.getValue().trim();
	if (keyWord == "") {
		return;
	}

	searchDs.baseParams = {
		'cmd' : 'info',
		'action' : 'findInfoFromEngine'
	};

	var nationality = nationCombobox.getValue();
	searchDs
			.load({
				params : {
					keyword : keyWord,
					start : startIndex,
					limit : pageSize,
					infoType : '人员',
					searchCmd : 'searchAcronymCategory',
					nationality : nationality
				},
				callback : function(r, options, success) {
					if (r.length == 0 && !success) {
						if (searchDs.reader.responseText == '[null]') {
							Ext.Msg
									.alert(
											TXT_common_hint,
											TXT_common_relogin,
											function() {
												window.location.href = '../eni/common/logout.jsp';
											});
							return;
						} else {
							Ext.Msg.alert(TXT_common_hint,
									TXT_SITE_CONFIGURATION_CHECK);
							return;
						}
					}
				}
			});
}

function loadDataFromDB() {
	var keyWord = searchKeyWordField.getValue().trim();
	if (keyWord == "") {
		return;
	}

	searchDs.baseParams = {
		'cmd' : 'personCommand',
		'action' : 'getPersonByName'
	};

	var nationality = nationCombobox.getValue();
	searchDs
			.load({
				params : {
					keyword : keyWord,
					start : startIndex,
					limit : pageSize,
					nationality : nationality,
					ulf : 'y',
					dataSourceKey : BestvSearch.DataSourceKey
				},
				callback : function(r, options, success) {
					if (r.length == 0 && !success) {
						if (searchDs.reader.responseText == '[null]') {
							Ext.Msg
									.alert(
											TXT_common_hint,
											TXT_common_relogin,
											function() {
												window.location.href = '../eni/common/logout.jsp';
											});
							return;
						} else {
							Ext.Msg.alert(TXT_common_hint,
									TXT_SITE_CONFIGURATION_CHECK);
							return;
						}
					}
				}
			});
}

function getPersonDetail(personId) {
	var grid = getPersonDetailPanel(personId);

	if (grid != null) {
		showWindow(grid, TXT_person_detail);
	}
};

function showWindow(panel, title) {
	var window = null;
	window = new Ext.Window({
		width : 750,
		height : 600,
		items : panel,
		region : 'center',
		plain : true,
		title : title,
		buttons : [ {
			text : TXT_common_close,
			handler : function() {
				if (window != null) {
					window.close();
				}
			}
		} ]

	});

	window.setPosition(250, 20);
	window.show();
}

function getPersonDetailPanel(personId) {
	var mod = searchModCombobox.getValue();
	var url = null;
	if (mod == 'index') {
		url = DISPATCH_URL
				+ "?cmd=info&action=findPersonDetailFromEngine&personId="
				+ personId + "&productFlag=0";
	} else {
		url = DISPATCH_URL
				+ "?cmd=personCommand&action=getPersonDetail&personId="
				+ personId + "&dataSourceKey=" + BestvSearch.DataSourceKey
				+ "&ulf=y";
	}

	var conn = Ext.lib.Ajax.getConnectionObject().conn;
	conn.open("GET", url, false);
	conn.send(null);
	if (conn.responseText == '[null]') {
		Ext.Msg.alert(TXT_common_hint, TXT_common_relogin, function() {
			window.location.href = '../eni/common/logout.jsp';
		});
		return null;
	} else if (conn.responseText != '') {
		var person = eval(conn.responseText);
		if (person != null && person.length > 0) {
			var products = eval(person[0].products);

			var honor = person[0].honor;
			if (honor != null && honor != '') {
				var raRegExp = new RegExp(',', 'g');
				honor = honor.replace(raRegExp, '<br>');
			}

			var productsStr = "";
			if (person[0].products != null && person[0].products != '') {
				for ( var i = 0; i < products.length; i++) {
					var onlineInfos = eval(products[i].onlineInfos);
					productsStr += products[i].year;
					productsStr += "	";
					productsStr += products[i].name;
					if (onlineInfos != null && onlineInfos.length > 0) {
						productsStr += "(";
						for ( var j = 0; j < onlineInfos.length; j++) {
							productsStr += "<font color='green'>"
									+ onlineInfos[j].name + "</font>";
							if (j != onlineInfos.length - 1) {
								productsStr += ", ";
							}
						}
						productsStr += ")";
					}
					productsStr += "	";
					productsStr += products[i].category;
					productsStr += "	";
					productsStr += products[i].description;
					productsStr += "<br>";
				}
			}

			var detailsTableXml = "<table border=0 cellspacing=1 width=680 bgcolor='#000000' style='margin: 20px 20px 20px 20px'>";

			// first row, name, gender, avatar
			detailsTableXml += "<tr bgcolor='#FFFFFF'>";
			detailsTableXml += "<td height=30 width=80  align='center'>姓	名</td><td height=30 width=150  align='center'>"
					+ person[0].name
					+ "</td><td height=30 width=80  align='center'>性	别</td><td height=30 width=150  align='center'>"
					+ person[0].gender
					+ "</td><td rowspan=4 colspan=2 align='center' valign='top'><img src='"
					+ person[0].avatar + "' height=140 width=120></img></td>";
			detailsTableXml += "</tr>";

			// second row, nationality,heights
			detailsTableXml += "<tr bgcolor='#FFFFFF'>";
			detailsTableXml += "<td height=30 width=80  align='center'>国	籍</td><td height=30 width=150  align='center'>"
					+ person[0].nationality
					+ "</td><td height=30 width=80  align='center'>身	高</td><td height=30 width=150  align='center'>"
					+ person[0].height + "</td>";
			detailsTableXml += "</tr>";

			// third row, birthday,home place
			detailsTableXml += "<tr bgcolor='#FFFFFF'>";
			detailsTableXml += "<td height=30 width=80  align='center'>生	日</td><td height=30 width=150  align='center'>"
					+ person[0].birthday
					+ "</td><td height=30 width=80  align='center'>家	乡</td><td height=30 width=150  align='center'>"
					+ person[0].homeplace + "</td>";
			detailsTableXml += "</tr>";

			// fourth row, blood type, constellation
			detailsTableXml += "<tr bgcolor='#FFFFFF'>";
			detailsTableXml += "<td height=30 width=80  align='center'>星	座</td><td height=30 width=150  align='center'>"
					+ person[0].constellation
					+ "</td><td height=30 width=80  align='center'>血	型</td><td height=30 width=150  align='center'>"
					+ person[0].bloodtype + "</td>";
			detailsTableXml += "</tr>";

			// fifth row, alias
			detailsTableXml += "<tr bgcolor='#FFFFFF'>";
			detailsTableXml += "<td height=30 width=80  align='center'>别	名</td><td height=30 colspan=5  align='left'  style='padding-left:10px'>"
					+ person[0].alias + "</td>";
			detailsTableXml += "</tr>";

			// sixth row, alias
			detailsTableXml += "<tr bgcolor='#FFFFFF'>";
			detailsTableXml += "<td height=30 width=80  align='center'>介	绍</td><td height=30 colspan=5  align='left'  style='padding-top:5px; padding-left:10px; padding-bottom:10px'>"
					+ "&nbsp;&nbsp;&nbsp;&nbsp;"
					+ person[0].description
					+ "</td>";
			detailsTableXml += "</tr>";

			// seventh row, honor
			detailsTableXml += "<tr bgcolor='#FFFFFF'>";
			detailsTableXml += "<td width=80  align='center' valign='top' style='padding-top:10px'>荣	誉</td><td colspan=5  align='left' style='padding-top:5px; padding-left:10px; padding-bottom:10px'>"
					+ honor + "</td>";
			detailsTableXml += "</tr>";

			// egighth row, honor
			detailsTableXml += "<tr bgcolor='#FFFFFF'>";
			detailsTableXml += "<td width=80  align='center' valign='top' style='padding-top:10px'>作	品</td><td colspan=5  align='left' style='padding-top:5px; padding-left:10px; padding-bottom:10px'>"
					+ productsStr + "</td>";
			detailsTableXml += "</tr>";
			detailsTableXml += "</table>";

			var panel = new Ext.Panel({
				border : false,
				align : 'left',
				region : 'center',
				autoScroll : true,
				height : 500,
				width : 740,
				items : {
					html : detailsTableXml
				}
			});
			return panel;
		}
	}
	return null;
}

function openUploadAvataForm(id) {
	var personDiv = document.getElementById(id);
	if (personDiv != null) {
		if (personDiv.childNodes.length <= 1) {
			var uploadAvatarBtn = new Ext.Button(
					{
						id : 'uploadAvatarBtn',
						text : TXT_common_save,
						type : "button",
						width : 60,
						height : 30,
						handler : function() {
							var filePath = form.getForm().findField(
									"avatarFilePath").getValue();
							if (filePath != null && filePath.length != '') {
								if (filePath.toLowerCase().endWith(".gif")
										|| filePath.toLowerCase().endWith(
												".jpg")
										|| filePath.toLowerCase().endWith(
												".jpeg")
										|| filePath.toLowerCase().endWith(
												".png")
										|| filePath.toLowerCase().endWith(
												".bmp")) {
									form.getForm().submit({
										success : function(form, action) {
											Ext.Msg.alert('信息', '上传成功！');
										},
										failure : function() {
											Ext.Msg.alert('错误', '上传失败');
										}
									});
								} else {
									Ext.Msg
											.alert('错误',
													'请选择[.gif, .jpg, .jpeg, .png, .bmp]的图片类型。');
								}
							} else {
								Ext.Msg.alert('错误', '请选择头像！');
							}
						}
					});

			var url = DISPATCH_URL
					+ "?cmd=personCommand&action=uploadAvatar&personId=" + id
					+ "&dataSourceKey=" + BestvSearch.DataSourceKey + "&ulf=y";

			var form = new Ext.form.FormPanel({
				renderTo : id,
				labelAlign : 'right',
				title : '',
				labelWidth : 0,
				frame : false,
				url : url,
				fileUpload : true,
				layout : 'column',
				border : false,
				bodyBorder : false,
				items : [ {
					xtype : 'textfield',
					fieldLabel : TXT_common_File,
					name : 'avatarFilePath',
					inputType : 'file',
					style : 'margin:0 2px 0 0px;',
					columnWidth : .88,
					height : 30
				}, {
					style : 'margin:2px 2px 0 5px;',
					columnWidth : .12,
					items : [ uploadAvatarBtn ]
				} ]
			});
		}
	}
}
